package com.zhuang.springmvc.controller;

import com.zhuang.springmvc.dao.EmployeeDao;
import com.zhuang.springmvc.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * description: EmployeeController
 * date: 2022/10/9 22:16
 * author: Zhuang
 * version: 1.0
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;

    @GetMapping(value = "/employee")
    public String getAllEmployee(Model model) {
        //获取所有的员工信息
        Collection<Employee> allEmployee = employeeDao.getAll();
        //将所有的员工信息在请求域中共享
        model.addAttribute("allEmployee", allEmployee);
        //跳转到列表页面
        return "employee_list";
    }

    @PostMapping(value = "/employee")
    public String addEmployee(Employee employee) {
        //保存员工信息
        employeeDao.save(employee);
        //重定向到列表功能：/employee
        return "redirect:/employee";
    }

    @GetMapping(value = "/employee/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model) {
        //根据id查询员工信息
        Employee employee = employeeDao.get(id);
        //将员工信息共享到请求域中
        model.addAttribute("employee", employee);
        //跳转到employee_update.html
        return "employee_update";
    }

    @PutMapping(value = "/employee")
    public String updateEmployee(Employee employee) {
        //修改员工信息
        employeeDao.save(employee);
        //重定向到列表功能：/employee
        return "redirect:/employee";
    }

    @DeleteMapping(value = "/employee/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id) {
        //删除员工信息
        employeeDao.delete(id);
        //重定向到列表功能：/employee
        return "redirect:/employee";
    }

}
